<template>
  <div class="addsports">
    <div class="titleImg"><img src="~assets/sports/ridingTitle.png" alt=""></div>
    <div class="title">上传运动</div>

    <group class="groupLine">
      <selector title="运动类型" placeholder="请选择" v-model="sportsDto.type" :options="sportTpyes" direction="rtl"></selector>
    </group>
    <group class="groupLine">
      <datetime-range title="运动时间点" placeholder="请选择" :start-date="sDate" :end-date="eDate" format="YYYY年MM月DD日" v-model="selectSportTime" @on-change="onChangeSportTime"></datetime-range>
    </group>
    <group class="groupLine">
      <selector title="运动时长" placeholder="请选择" v-model="sportsDto.sportScope" :options="sportScopes" direction="rtl"></selector>
    </group>

    <group class="report__group">
      <div class="report__group_row" v-for="(item,index) in listNo" :key="index">
        <!-- 单选 -->
        <input :id="'file'+index" type="file" accept="image/*" @change="onFileChange($event,index)" v-show="false">
        <!-- 多选 -->
        <!-- <input :id="'file'+index" type="file" multiple size="20" accept="image/*" @change="onFileChange($event,index)" v-show="false"> -->
        <div class="row_label">
          <div v-if="titleList[index].sonTile.length===0">{{titleList[index].title}}</div>
          <div v-else>
            <span>{{titleList[index].title}}</span>
            <span class="sp">{{titleList[index].sonTile[0].title}}</span>
          </div>
        </div>
        <img class="addImages" @click="addPic(index)" src="~assets/x3/ico/x3_addImg.png">
        <div class="report__group_row_imgs" v-show="sportsDto['showImages'+(index)].length >0">
          <div class="img" v-for="(image,i) in sportsDto['showImages'+(index)]" :key="i" @click="delImg(index, i, image.name)">
            <img :src="image.data" :alt="i" />
          </div>
          <!-- <x-button @click.native="removeImageOfRow(index)">移除全部图片</x-button> -->
        </div>
        <div class="insure__footer">
          <x-button class="report__rightbtn" type="primary" action-type="button" @click.native="subForm()" :disabled="isDisabled">提交申请</x-button>
        </div>
      </div>
    </group>

    <toast v-model="showToast" type="warn" position="default" :time="2000">{{showToastText}}</toast>
  </div>
</template>

<script>
import WeChatOauthEnterprise from "src/js/weChat/weChatOauthEnterprise"; //引入企业微信授权js
import DateUtil from "src/common/util/dateUtil";
import Validation from "src/common/util/validation";
import { RequestUrl } from "src/common/url";
import { mapState } from 'vuex';
import { Mutations, RouteUrl, SaveName, StrLenth } from "src/common/const";
import { XInput, XButton, Toast, Group, Selector, DatetimeRange } from "vux";
import { debug } from 'util';
export default {
  components: { XInput, XButton, Toast, Group, Selector, DatetimeRange },
  computed: mapState(["isWeChar"]),
  data() {
    return {
      StrLenth: {}, //字符长度常量
      showToast: false, //提示信息
      showToastText: "", //提示信息
      isDisabled: false,//是否可提交
      sportTpyes: [
        { key: '跑步', value: '跑步' },
        { key: '骑行', value: '骑行' },
        { key: '游泳', value: '游泳' },
        { key: '跳绳', value: '跳绳' },
        { key: '瑜伽', value: '瑜伽' },
        { key: '单双杠', value: '单双杠' },
        { key: '哑|杠|壶铃', value: '哑|杠|壶铃' },
        { key: '其他运动', value: '其他运动' },
      ],
      selectSportTime: [],// ["2018-01-01", "00", "00"],//默认运动时间点
      //减去一周的时间,yyyy-mm-dd
      sDate: DateUtil.getDateStr_YmdByTs(DateUtil.getDateByStrYmdOrYmdhms(DateUtil.getSubMonth(new Date()))),
      //当前时间,yyyy-mm-dd
      eDate: DateUtil.getDateStr_YmdByTs(new Date()),
      //运动时长列表
      sportScopes: [
        { key: '0~10', value: '10min≥' },//因组件对齐方式使用了相反符号
        { key: '10~30', value: '10min~30min' },
        { key: '30~60', value: '30min~60min' },
        { key: '60~90', value: '60min~90min' },
        { key: '90~120', value: '90min~120min' },
        { key: '120~180', value: '2-3小时' },
        { key: '180~360', value: '接近半天' },
        { key: '360~720', value: '一整天' },
      ],
      department: "",//部门信息
      userList: [],//用户列表
      userInfo: "",//用户信息

      listNo: 1,//上传图片的 模块和子数组个数
      titleList: [
        // { title: "手续", sonTile: [] },
        // { title: "运动照片", sonTile: [{ title: "(必选)" }] }
        { title: "运动照片", sonTile: [] }
      ],
      sportsDto: {

        // departmentId: "15",// 部门ID
        // departmentName: "信息技术部",// 部门名称
        // userId: "Dylanqiu",// 账号ID
        // userName: "邱琼龙",// 账号名称

        departmentId: "",// 部门ID
        departmentName: "",// 部门名称
        userId: "",// 账号ID
        userName: "",// 账号名称
        type: "",// 运动类型标识
        sportTime: "",// 运动时间点
        sportScope: "",// 运动时间范围

        showImages0: [],//界面显示的图片数组
        // showImages1: [],//界面显示的图片数组
        // showImages2: [],//界面显示的图片数组
        // showImages3: [],//界面显示的图片数组
        // showImages4: [],//界面显示的图片数组
        uploadAllImages: [],//上传的图片数组
      },
    }
  },
  methods: {
    //选择运动时间点
    onChangeSportTime(valArray) {
      this.sportsDto.sportTime = valArray[0] + " " + valArray[1] + ":" + valArray[2] + ":00";
    },
    //触发选择文件事件
    addPic(index) {
      //IOS系统需要调用2次才能触发到click
      if (localStorage["BOTYPE"] == "I") {
        $("#file" + index).trigger('click');
        $("#file" + index).trigger('click');
      } else {
        $("#file" + index).trigger('click');
      }
      return;
    },
    //根据选择的第几个栏目的图片，对应创建图片阅读器并显示图片
    onFileChange(event, index) {
      switch (index) {
        case 0: this.createImage(event, index, "imageFileOne"); break;
        // case 1: this.createImage(event, index, "imageFileTwo"); break;
        // case 2: this.createImage(event, index, "imageFileThree"); break;
        // case 3: this.createImage(event, index, "imageFileFour"); break;
        // case 4: this.createImage(event, index, "imageFileFive"); break;
        default: break;
      }
    },
    //创建图片
    createImage(obj, index, filePrdfix) {
      let files = obj.target.files || obj.dataTransfer.files;
      if (!files.length) return;
      if (this.isNotImgFile(files)) {
        this.$vux.alert.show({ content: this.$common.alertMsg("请选择图片文件！", "red;") });
        return;
      }
      if (typeof FileReader === 'undefined') {
        this.$vux.alert.show({ content: this.$common.alertMsg("您的浏览器不支持图片上传，请升级您的浏览器", "red;") });
        return;
      }
      let leng = files.length;
      if (leng > 10) {
        this.showToastText = "最多选10张~";
        this.showToast = true;
        return;
      }
      if (this.sportsDto.uploadAllImages.length > 0) {
        this.showToastText = "最多选1张~";
        this.showToast = true;
        return;
      }
      for (let i = 0; i < leng; i++) {
        //源文件
        let nowFile = files[i];
        //创建新名称的原文件
        let newFile = new File([nowFile], filePrdfix + "_" + DateUtil.getNowDateStrYmdhms() + "-" + i + ".jpg", { type: "image/jpeg" });
        // console.log("新文件大小====" + newFile.size + "bit");
        if (newFile.size > 1048576) {
          this.showToastText = "文件大小不能超过1MB";
          this.showToast = true;
          return;
        }
        let newFileName = newFile.name;
        //输出到界面
        let _this = this;
        let reader = new FileReader();
        reader.readAsDataURL(nowFile);
        reader.onload = function (event) {
          //根据模块追加图片
          _this.sportsDto['showImages' + index].push({ data: event.target.result, name: newFileName });
        };
        //存放到上传图片数组中
        this.sportsDto.uploadAllImages.push(newFile);
      }
    },
    //移除当前模块单个文件
    delImg(index, i, fileName) {
      //index=外循环下标
      //i = 内循环下标
      for (let j = 0; j < this.sportsDto.uploadAllImages.length; j++) {
        let file = this.sportsDto.uploadAllImages[j];
        if (fileName == file.name) {
          //删除上传数组中指定名称的文件
          this.sportsDto.uploadAllImages.splice(j, 1);
          break;
        }
      }
      //移除当前模块单个文件
      this.sportsDto['showImages' + index].splice(i, 1);
    },
    //移除当前模块全部文件
    removeImageOfRow(index) {
      let upFiles = this.sportsDto.uploadAllImages;
      let showFiles = this.sportsDto['showImages' + index];
      for (let i = 0; i < upFiles.length; i++) {
        for (let j = 0; j < showFiles.length; j++) {
          if (showFiles[j].name == upFiles[i].name) {
            //删除上传数组中指定名称的文件
            this.sportsDto.uploadAllImages.splice(i, 1);
          }
        }
      }
      //移除当前模块全部文件
      this.sportsDto['showImages' + index] = [];
    },
    // 检查是否为非图像文件
    isNotImgFile(files) {
      for (let i = 0; i < files.length; i++) {
        let t = files[i].type;
        if (!/image\/\w+/.test(t)) {
          return true;
        }
      }
    },
    //获取文件大小
    getFileSize(base64Code) {
      let str = base64Code.substring(22);
      let equalIndex = str.indexOf('=');
      if (str.indexOf('=') > 0) {
        str = str.substring(0, equalIndex);
      }
      let strLength = str.length;//原始大小
      let fileLength = Math.ceil(parseInt(strLength - (strLength / 8) * 2) / 1024);;
      return fileLength;
    },

    //提交合作申请
    subForm() {
      // let qyWeChat = localStorage[SaveName.LOCAL_STORAGE_USER_ENTERPRISE];
      // alert("本页数据：" + this.qyWeChat);
      //校验
      if (Validation.isEmpty(this.sportsDto.departmentId)) {
        this.showToastText = "部门ID为空"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.departmentName)) {
        this.showToastText = "部门名称为空"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.userId)) {
        this.showToastText = "账号ID为空"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.userName)) {
        this.showToastText = "账号名称为空"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.type)) {
        this.showToastText = "请选择类型"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.sportTime)) {
        this.showToastText = "请选择时间点"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.sportScope)) {
        this.showToastText = "请选择时间范围"; this.showToast = true; return;
      }
      if (Validation.isEmpty(this.sportsDto.uploadAllImages) || this.sportsDto.uploadAllImages.length < 1) {
        this.showToastText = "请上传图片"; this.showToast = true; return;
      }
      let formData = new FormData();
      for (let index = 0; index < this.sportsDto.uploadAllImages.length; index++) {
        let element = this.sportsDto.uploadAllImages[index];
        formData.append("imgFiles", element);
      }
      formData.append("departmentId", this.sportsDto.departmentId);
      formData.append("departmentName", this.sportsDto.departmentName);
      formData.append("userId", this.sportsDto.userId);
      formData.append("userName", this.sportsDto.userName);
      formData.append("type", this.sportsDto.type);
      formData.append("sportTime", this.sportsDto.sportTime);
      formData.append("sportScope", this.sportsDto.sportScope);
      let _this = this;
      _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
      _this.$http.post(RequestUrl.INSERT_SPORT, formData).then(function (res) {
        _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
        if (res.state != 0) {
          _this.showToastText = res.result;
          _this.showToast = true;
          return;
        }
        _this.$common.showMsg(_this, "上传运动信息成功", "gredn", true);

        //清空全部图片
        _this.removeImageOfRow(0);
        _this.sportsDto.type = "";// 清空运动类型标识
        _this.sportsDto.sportTime = "";// 清空运动时间点
        _this.selectSportTime = [];//时间点显示变量
        _this.sportsDto.sportScope = "";// 清空运动时间范围
      });
    },
    //初始化部门列表（已废）
    initDepartmentList() {
      let _this = this;
      _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
      _this.$http.post(RequestUrl.DEPARTMENT_LIST).then(function (res) {
        _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);

        if (res.state == 0) {
          let list = res.result;
          for (let index = 0; index < list.length; index++) {
            let element = list[index];
            // if (element.parentid == 1) {
            let obj = { key: element, value: element.name };
            _this.departmentList.push(obj);//部门列表
            // }
          }
        }
      });
    }
  },
  mounted() {
    document.title = "运动";
    this.StrLenth = StrLenth; //字符长度常量
    this.$init.subPageInit(this);
    // this.initDepartmentList();

    let qyWeChat = localStorage[SaveName.LOCAL_STORAGE_USER_ENTERPRISE];
    if (this.$common.isNotEmpty(qyWeChat)) {
      // alert("加载qyWeChat=" + qyWeChat);
      let qyUserInfo = eval("(" + qyWeChat + ")");
      this.sportsDto.departmentId = qyUserInfo.departmentId;// 部门ID
      this.sportsDto.departmentName = qyUserInfo.departmentName;// 部门名称
      this.sportsDto.userId = qyUserInfo.userid;// 账号ID
      this.sportsDto.userName = qyUserInfo.name;// 账号名称
      this.isDisabled = false;//可提交表单

      //userid有效
      if (this.$common.isNotEmpty(this.sportsDto.userId)) {
        let _this = this;
        //根据userId查询数据库的企业微信账户，获取数据库最新数据
        let initData = { TYPE: "FORM", userId: _this.sportsDto.userId, };
        _this.$http.post(RequestUrl.GET_USER_BY_USER_ID, initData).then(function (res) {
          if (res.state == 0) {
            //保存USER_INFO信息
            localStorage[SaveName.LOCAL_STORAGE_USER_ENTERPRISE] = JSON.stringify(res.result);
            //刷新最新数据库数据
            _this.sportsDto.departmentId = res.result.departmentId;// 部门ID
            _this.sportsDto.departmentName = res.result.departmentName;// 部门名称
            _this.sportsDto.userId = res.result.userid;// 账号ID
            _this.sportsDto.userName = res.result.name;// 账号名称
            return;
          } else {
            if (res.result.indexOf("不存在") > 0) {
              // alert("发起授权");
              WeChatOauthEnterprise.weChatOauth(_this, "myparameters");
            }
          }
        });
      }
    } else {
      // alert("发起授权");
      WeChatOauthEnterprise.weChatOauth(this, "myparameters");
    }
  }
}
</script>

<style lang="scss" scoped>
.addsports {
  width: 90%;
  margin: 0px auto;

  .groupLine {
    margin: 0px auto;
    border-radius: 5px;
    .weui-cells {
      border-radius: 5px;
    }
  }
  .titleImg {
    padding-top: 20px;
    margin: 0px auto;
    text-align: center;
    img {
      width: 40px;
      height: 40px;
    }
  }
  .title {
    font-size: 24px;
    text-align: center;
    margin: 0px auto;
    color: #67a926;
    margin-bottom: 5px;
  }

  .report__group {
    width: 100%;
    .weui-cells {
      padding: 5px 0px 80px 0px;
    }
  }
  .report__group_row {
    border: 1px solid #e7e7e7;
    margin: 15px 15px;
    padding: 10px 0px;
    height: max-content;
    margin-bottom: 100px;
    .row_label {
      // /* width: 120px; */
      // height: 100%;
      // /* float: left; */
      // text-align: center;

      /* width: 120px; */
      height: 100%;
      line-height: 50px;
      float: left;
      text-align: center;
      margin-left: 10px;
      margin-right: 10px;

      div {
        width: 100%;
        height: 20px;
        font-size: 14px;
        text-align: center;
        span {
          width: 100%;
        }
        .sp {
          font-size: 10px;
          color: #aaa;
        }
      }
      img {
        display: block;
        clear: both;
        width: 50px;
        height: auto;
        margin: 0px auto;
      }
    }
    .addImages {
      // clear: both;
      // display: block;
      // width: 50px;
      // height: auto;
      // margin-top: 12px;
      // margin-left: auto;
      // margin-right: auto;

      width: 50px;
    }
  }
  .report__group_row_imgs {
    border-top: 1px solid #e7e7e7;
    padding: 10px;
    margin-top: 10px;
    .img {
      display: block;
      // float: left;
      // width: 48px;
      // height: 48px;
      width: 90%;
      margin: 5px;
      border: 1px solid #ccc;
      padding: 10px;
      background: #ffffff url(~assets/x3/ico/close.png) no-repeat right top;
      img {
        display: block;
        width: 100%;
        height: 100%;
        margin: auto;
      }
    }
    .btn {
      width: 100%;
      margin: 10px auto;
      clear: both;
    }
  }

  .insure__footer {
    clear: both;
    position: fixed;
    padding-bottom: 20px;
    padding-top: 10px;
    z-index: 5;
    background-color: white;
    div {
      height: 100%;
      line-height: 47px;
      text-align: center;
      font-size: 20px;
    }
    // box-shadow: 0px 0px 0px 0px #efefef !important;
    box-shadow: 0px 0px 10px 1px #efefef;
  }

  .report__rightbtn {
    width: 90%;
    height: 47px;
    background: #c8161d;
    color: #fff;
  }
}

//修改默认按钮失效时背景颜色
.weui-btn_disabled.weui-btn_primary {
  background-color: #cfcfcf;
}
</style>

